package com.wl.dzt.basic.shir;

import com.wl.dzt.basic.entity.BasicOrganization;
import com.wl.dzt.basic.entity.BasicPosition;
import com.wl.dzt.basic.entity.BasicUser;
import com.wl.dzt.basic.service.callback.SmsSendSwitchCallback;
import com.wl.dzt.basic.user.User;
import com.wl.dzt.sys.controller.annotation.Shir;
import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.param.shir.ShirHandler;
import com.wl.dzt.sys.controller.param.shir.ShirTypes;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.core.dao.select.term.Term;
import com.wl.dzt.sys.util.AliyunSmsUtils;
import com.wl.dzt.sys.util.DynaBean;
import com.wl.dzt.sys.util.PwdUtils;
import com.wl.dzt.sys.util.WebUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * <b>用户拦截器</b>
 * <p>
 *
 * </p>
 */

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/19/019
 * @description 用户拦截器
 */
@Component
public class BasicUserShir {
    public static Random random = new Random(100000);

    /**
     * <b>注册用户</b>
     * <p>
     * 用户注册成功之后发送短信(中间拦截)
     * </p>
     */
    @Shir(ShirTypes.MIDDLE)
    public String userSaveShri(ShirHandler handler) {
        Param param = handler.getParam();
        BasicUser user = (BasicUser) param.getEntity();
        user.setUname(user.getPhone());
        user.setPwd(PwdUtils.MD5("888888"));
        String url = handler.invoke();
        if (param.isSuccess()) {
            //发送短信
            Optional<BasicOrganization> optOrg = Optional.ofNullable(user.getOrganId());
            optOrg.orElseGet(() -> {
                BasicUser tempUser = DB.get(BasicUser.class, user.getId(), "organId.id");
                return tempUser.getOrganId();
            });
            SmsSendSwitchCallback.handler(optOrg.get().getId(), () -> AliyunSmsUtils.send(user.getPhone(), "SMS_139227797", new DynaBean().set("name", user.getName()).set("uname", user.getUname()).set("pwd", "888888")));
        }
        return url;
    }

    /**
     * <b>树形拦截</b>
     * <p>
     * 动态根据条件查询组织机构下的人员
     * </p>
     *
     * @param param
     * @return
     */
    @Shir(ShirTypes.BEFORE)
    public boolean userOrgTreeShir(Param param) {
        List<Term> list = param.getTerms();
        if (list.isEmpty()) {
            Set<String> orgsIds = new HashSet<>();
            User user = WebUtils.getUser(param.getRequest());
            caseOrgnUserIds(orgsIds, user.getAttr("areaId") + "");
            list.add(Term.in("organId.id", orgsIds.toArray(new String[orgsIds.size()])));
        } else {
            int remove = -1;
            Term addTerm = null;
            for (int i = 0; i < list.size(); i++) {
                Term term = list.get(i);
                if ("organId.id".equalsIgnoreCase(term.getField())) {
                    Set<String> orgsIds = new HashSet<>();
                    caseOrgnUserIds(orgsIds, term.getValue().toString());
                    if (!orgsIds.isEmpty()) {
                        remove = i;
                        addTerm = Term.in(term.getField(), orgsIds.toArray(new String[orgsIds.size()]));
                    }
                }
            }
            if (remove != -1) {
                list.remove(remove);
            }
            if (addTerm != null) {
                list.add(addTerm);
            }
        }
        list.add(Term.notLike("id", "admin"));
        return true;
    }

    /**
     * <b>迭代部门</b>
     * <p>
     * 递归查询出一个组织机构下所有的子组织机构
     * </p>
     *
     * @param orgsIds
     * @param oid
     */
    private void caseOrgnUserIds(Set<String> orgsIds, String oid) {
        // 查询出子组织机构
        List<BasicOrganization> list = DB.list(Select.create(BasicOrganization.class).where(Term.eq("organParentId.id", oid)));
        orgsIds.add(oid);
        list.forEach(organ -> {
            orgsIds.add(organ.getId());
            caseOrgnUserIds(orgsIds, organ.getId());
        });
    }
}
